package io.github.lee.jel.ui.item.play

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.util.Log
import android.widget.SeekBar
import androidx.activity.viewModels
import androidx.core.net.toUri
import androidx.core.os.bundleOf
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.core.ui.BaseActivity
import io.github.lee.core.util.getBundleParcelable
import io.github.lee.core.util.getBundleValue
import io.github.lee.jel.R
import io.github.lee.jel.databinding.ActivityMediaPlayBinding
import io.github.lee.jel.domain.Item
import io.github.lee.jel.global.session

@AndroidEntryPoint
class MediaPlayActivity : BaseActivity<ActivityMediaPlayBinding, MediaPlayVM>() {

    companion object {
        private const val KEY_ITEM = "ITEM"

        @JvmStatic
        fun start(context: Context, item: Item) {
            val starter = Intent(context, MediaPlayActivity::class.java)
                .putExtras(
                    bundleOf(
                        KEY_ITEM to item
                    )
                )
            context.startActivity(starter)
        }
    }

    override fun onCreateViewModel(): MediaPlayVM =
        viewModels<MediaPlayVM>().value

    override fun onCreateSuccess(): ActivityMediaPlayBinding =
        ActivityMediaPlayBinding.inflate(layoutInflater)


    override fun onObserved() {
        super.onObserved()
        vm?.apply {
            closeClickLiveData.observe(this@MediaPlayActivity) {
                if (it) {
                    finish()
                    closeClickLiveData.postValue(false)
                }
            }
            isPlayingLiveData.observe(this@MediaPlayActivity) {
                vb?.isPlaying = it
            }
        }
    }

    override fun onSetViewListener() {
        super.onSetViewListener()
    }


    override fun onSetViewData() {
        super.onSetViewData()
        statusBarColor(Color.TRANSPARENT, false)

        val insetsCtrl = WindowCompat.getInsetsController(window, window.decorView)
        insetsCtrl.hide(WindowInsetsCompat.Type.systemBars())

        val windowInsetsController =
            WindowCompat.getInsetsController(window, window.decorView)
        windowInsetsController.systemBarsBehavior =
            WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE


        val item = getBundleParcelable(KEY_ITEM, Item::class.java)
        if (null == item) {
            toast(getString(R.string.error_param_missing))
            finish()
            return
        }
//        http://localhost/
        vm?.item = item
//
//        http://jel.291700351.xyz/videos/
        // 4155b520-231d-9c29-2ff9-2df2ac5139a2/master.m3u8?
        // DeviceId=TW96aWxsYS81LjAgKFgxMTsgTGludXggeDg2XzY0OyBydjoxMjIuMCkgR2Vja28vMjAxMDAxMDEgRmlyZWZveC8xMjIuMHwxNzA3OTYxMDMwMTY4&
        // MediaSourceId=4155b520231d9c292ff92df2ac5139a2
        // &VideoCodec=h264
        // &AudioCodec=aac
        // &AudioStreamIndex=4
        // &VideoBitrate=139808000
        // &AudioBitrate=192000
        // &AudioSampleRate=44100
        // &MaxFramerate=60&PlaySessionId=f69c6ba3a14a437b89059d2172b8732a&
        // api_key=86a21c616aee442592d60421d4138899&TranscodingMaxAudioChannels=6
        // &RequireAvc=false
        // &Tag=87e2949a1d09b37c9873ca0a479d032b
        // &SegmentContainer=ts&MinSegments=1&BreakOnNonKeyFrames=True&hevc-level=153&hevc-videobitdepth=10&hevc-profile=main10&hevc-audiochannels=2&aac-profile=lc&TranscodeReasons=VideoCodecNotSupported%2C+AudioCodecNotSupported
        val streamUri = mContext.session?.address?.toUri()
            ?.buildUpon()
//            ?.appendEncodedPath("Videos/${item.id}/stream")
            ?.appendEncodedPath("Videos/${item.id}/master.m3u8")
            ?.appendQueryParameter("MediaSourceId", item.id)
            ?.appendQueryParameter("VideoCodec", "h264")
            ?.appendQueryParameter("AudioCodec", "aac")
            ?.appendQueryParameter("AudioStreamIndex", "4")
//            ?.appendQueryParameter("VideoBitrate", "139808000")
            ?.appendQueryParameter("AudioBitrate", "192000")
            ?.appendQueryParameter("AudioSampleRate", "44100")
            ?.appendQueryParameter("api_key", mContext.session?.accessToken)
            ?.build()
        if (null == streamUri) {
            toast(getString(R.string.error_param_missing))
            finish()
            return
        }

        Log.e("TAG", "play uri : $streamUri")
        vb?.vm = vm
        vb?.playerView?.player = vm?.setUri(streamUri)
        vm?.startPlay()

    }




}